import {ActionContext} from 'vuex';
import ListModule from '@/store/modules/list-module';
import ListState from '@/store/modules/list-state';
import Role from '@/store/entities/administration/role/role';
import Ajax from '@/lib/ajax';
import PageResult from '@/store/entities/page-result';

interface RoleState extends ListState<Role> {
    pagedRoles: any;
    roleForEdit: any;
    permissions: string[];
    allRoles: any[];
}

class RoleModule extends ListModule<RoleState, any, Role> {
    state = {
        totalCount: 0,
        currentPage: 1,
        pageSize: 10,
        list: [],
        loading: false,
        pagedRoles: {},
        roleForEdit: {},
        allRoles: [],
        permissions: [],
    };
    actions = {
        async obtainRoles(context: ActionContext<RoleState, any>, payload: any) {
            context.state.loading = true;
            const response = await Ajax.post('/api/services/app/Role/ObtainRoles', payload.data);
            context.state.loading = false;
            const page = response.data.result as PageResult<Role>;
            context.state.totalCount = page.totalCount;
            context.state.list = page.items;
        },
        async createOrUpdateRole(context: ActionContext<RoleState, any>, payload: any) {
            await Ajax.post('/api/services/app/Role/CreateOrUpdateRole', payload.data);
        },
        async deleteRole(context: ActionContext<RoleState, any>, payload: any) {
            await Ajax.delete('/api/services/app/Role/DeleteRole?Id='+payload.data.id);
        },
        async getRoleForEdit(context: ActionContext<RoleState, any>, payload: any) {
            const response = await Ajax.get('/api/services/app/Role/GetRoleForEdit?Id='+payload.data.id);
            context.state.roleForEdit = response.data.result;
        },
        async getAllRoles(context: ActionContext<RoleState, any>, payload: any) {
            const response = await Ajax.get('api/services/app/Role/GetAllRoles');
            context.state.allRoles = response.data.result.items;
        },
        async obtainPagedRoles(context: ActionContext<RoleState, any>, payload: any) {
            context.state.loading=true;
            const response = await Ajax.post('api/services/app/Role/ObtainRoles', payload.data);
            context.state.loading=false;
            context.state.pagedRoles = response.data.result;
        },
    };
    mutations = {
        setCurrentPage(state: RoleState, page: number) {
            state.currentPage = page;
        },
        setPageSize(state: RoleState, pageSize: number) {
            state.pageSize = pageSize;
        },
    };
}

const roleModule = new RoleModule();
export default roleModule;
